import { EventSourcePolyfill } from "event-source-polyfill"
import { getToken } from "./auth"
import store from "@/store"

export default class SSE {
  constructor(onMessage) {
    this.url = process.env.VUE_APP_BASE_API
    this.eventSource = null
    this.onMessage = onMessage
    this.userId = null
  }

  connect() {
    if (this.eventSource) {
      return
    }
    if (!window.EventSource) {
      return
    }
    this.eventSource = new EventSourcePolyfill(`${this.url}/sse/connect`, {
      heartbeatTimeout: 60 * 60 * 1000,
      headers: {
        token: getToken(),
      },
    })
    this.eventSource.onopen = (e) => {
      console.log("已建立SSE连接~")
    }
    this.eventSource.onmessage = (e) => {
      this.onMessage(e.data)
    }
    this.eventSource.onerror = (e) => {
      if (e.readyState == EventSource.CLOSED) {
        console.log("SSE连接关闭")
      } else if (this.eventSource.readyState == EventSource.CONNECTING) {
        console.log("SSE正在重连")
        // //重新设置token
        this.eventSource.headers = {
          token: getToken(),
        }
      } else {
        console.log("error", e)
      }
    }
    this.userId = store.state.user.id
  }
  disconnectSSE() {
    if (this.eventSource) {
      //   // 关闭SSE
      this.eventSource.close()
      fetch(`${this.url}/sse/disconnect/${this.userId}`, {
        method: "DELETE",
        keepalive: true,
      })
      this.eventSource = null
    }
  }
}
